package com.example.spider.common.config;

import com.example.spider.common.spider.RestSpider;
import com.example.spider.common.starter.SpiderStarterTrigger;
import com.example.spider.common.util.MyThreadFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lym
 */
@Configuration
public class SpiderAutoConfiguration {


    @Bean
    @ConditionalOnMissingBean
    public RestSpider restSpider() {
        return new RestSpider(newRestTemplate(StandardCharsets.UTF_8));
    }

    public static RestTemplate newRestTemplate(Charset charset) {
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> httpMessageConverter : list) {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(charset);
                break;
            }
        }
        return restTemplate;
    }

    public static final String SPIDER = "spiderThreadPool";

    @Bean(SPIDER)
    @Qualifier(SPIDER)
    public ThreadPoolExecutor spiderThreadPool(){
        return new ThreadPoolExecutor(4, 30, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(2000), new MyThreadFactory("SPIDER", true));
    }

    @Bean
    @ConditionalOnProperty(value = "spider.startAllAfterStar", havingValue = "true")
    public SpiderStarterTrigger spiderStarterTrigger(){
        return new SpiderStarterTrigger();
    }


}
